﻿using System;
using TSites.Common.Enums;
using System.Collections;
using TSites.Core.Domain.UserMangerment;
using TSites.Utility.Random;
using System.Text;
using Spring.Transaction.Interceptor;

namespace TSites.UserMgmt
{
	public class AdminMembership : AccountMembership, IAdminMembership
	{
		#region IAdminMembership Members

		public RET_CODE RetsetUserPassword(string userId, string updateUserId)
		{
			User currentUser = GetByUserId(userId);
			if (currentUser == null)
				return RET_CODE.USERID_DOES_NOT_EXISTED;

			string email = currentUser.Email;
			if (email == null || email.Length == 0)
				return RET_CODE.EMAIL_DOES_NOT_EXISTED;
			
			string salt, newPassword;
			newPassword = RandomProvider.Generate(_passwordLen);
			// email to user

			// update new generate password to DB
			string encryptPwd = EncryptProvider.ComputeHash(newPassword, out salt);
			currentUser.Password = encryptPwd;
			currentUser.Salt = salt;
			currentUser.UpdateDate = DateTime.Now;
			currentUser.UpdateUserId = updateUserId;
			currentUser.Reason = "Reset password by " + updateUserId;

			RET_CODE retCode = RET_CODE.ERROR;
			try
			{
				UserDaoProvider.Update(currentUser);
				retCode = RET_CODE.SUCCESS;
			}
			catch (Exception ex)
			{
				retCode = RET_CODE.DB_ERROR;
				Error(ex.Message, ex);
			}

			return retCode;
		}

		public RET_CODE DeleteUser(string userId)
		{
			RET_CODE retCode = RET_CODE.ERROR;
			User currentUser;
			try
			{
				currentUser = GetByUserId(userId);
				if (currentUser == null)
				{
					retCode = RET_CODE.USERID_DOES_NOT_EXISTED;
				}
				else
				{
					UserDaoProvider.Delete(currentUser);
					retCode = RET_CODE.SUCCESS;
				}
			}
			catch (Exception ex)
			{
				retCode = RET_CODE.DB_ERROR;
				Error(ex.Message, ex);
			}

			return retCode;
		}

		public RET_CODE UpdateActiveCode(string userId, int activeCode, string reason, string updateUserId)
		{
			RET_CODE retCode = RET_CODE.ERROR;
			try
			{
				int effectedRow = UserDaoProvider.ExecuteNonQuery("SP_UPD_USER_MGMT_ACTIVECODE",
					new object[] { userId, activeCode, reason, updateUserId });

				retCode = effectedRow > 0 ? RET_CODE.SUCCESS : RET_CODE.DB_ERROR;
			}
			catch (Exception ex)
			{
				retCode = RET_CODE.DB_ERROR;
				Error(ex.Message, ex);
			}

			return retCode;
		}

		public IList GetUsers(string uid, string username, string email, int activeCode,
			int pageIndex, int pageSize, out int totalItem)
		{
			return UserDaoProvider.GetUserList(uid, username, email, (int)activeCode, pageIndex, pageSize, out totalItem);
		}

		#endregion

        [Transaction]
        public new RET_CODE RegisterUser(User entity)
        { 
            // generate random password
            entity.Password = GeneratePassword();
            return base.RegisterUser(entity);
        }
	}
}
